package sql_db

import "database/sql"

func QuerySql(db *sql.DB, sql string) (results []map[string]string, err error) {
	query, err := db.Query(sql)
	if err != nil {
		return nil, err
	}
	cols, _ := query.Columns()
	values := make([][]byte, len(cols))
	scans := make([]interface{}, len(cols))
	for i := range values {
		scans[i] = &values[i]
	}
	var colLabel []map[string]string

	for _, value := range cols {
		colCodeName := make(map[string]string)
		colCodeName["colName"] = value
		colCodeName["colCode"] = value
		colLabel = append(colLabel, colCodeName)
	}

	var rowResults []map[string]string
	for query.Next() {
		if err := query.Scan(scans...); err != nil { // --query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
			return nil, err
		}

		row := make(map[string]string)

		for k, v := range values {
			key := cols[k]
			row[key] = string(v)
		}
		rowResults = append(rowResults, row)
	}
	return rowResults, nil
}
